<template>
  <el-row :gutter="20">
    <el-col :span="4">
      <div class="nav">
        <div class="nav-title">产品类型列表</div>
        <div class="treeProduct">
          <treeProduct @sendTreeData="sendTreeData"></treeProduct>
        </div>
      </div>
    </el-col>
    <el-col :span="20">
      <div class="wrapper">
        <div class="wrapper-title">商品{{ title }}</div>

        <!-- 表单 -->
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="所属分类" prop="category">
            <span>{{ ruleForm.category }}</span>
          </el-form-item>
          <el-form-item label="商品名称" prop="title">
            <el-input v-model="ruleForm.title"></el-input>
          </el-form-item>
          <el-form-item label="商品价格" prop="price">
            <el-input v-model="ruleForm.price"></el-input>
          </el-form-item>
          <el-form-item label="商品数量" prop="num">
            <el-input v-model="ruleForm.num"></el-input>
          </el-form-item>
          <el-form-item label="商品卖点" prop="sellPoint">
            <el-input v-model="ruleForm.sellPoint"></el-input>
          </el-form-item>
          <el-form-item label="添加图片" prop="image">
            <uploadImg @sendImg="sendImg" ref="upload" :fileList="fileList"></uploadImg>
          </el-form-item>
          <el-form-item label="商品描述" prop="descs">
            <wangEditor @sendWangEditor="sendWangEditor" ref="wangEditor"></wangEditor>
          </el-form-item>

          <el-form-item label="首页轮播推进" prop="isShow">
            <el-switch v-model="ruleForm.delivery"></el-switch>
          </el-form-item>
          <el-form-item label="是否推荐商品" prop="isShow">
            <el-switch v-model="ruleForm.delivery"></el-switch>
          </el-form-item>
          <el-form-item label="是否上架商品" prop="isShow">
            <el-switch v-model="ruleForm.delivery"></el-switch>
          </el-form-item>

          <el-form-item> 
            <el-button v-show='title!="详情"' type="primary" @click="submitForm('ruleForm')">提交</el-button>
            <el-button v-show='title!="详情"' @click="resetForm('ruleForm')">重置</el-button>
            <el-button @click="closePage">取消</el-button>
          </el-form-item>
        </el-form>

      </div>
    </el-col>
  </el-row>
</template>

<script>
import { mapState } from 'vuex'
import treeProduct from './treeProduct.vue'
import uploadImg from './uploadImg.vue'
import wangEditor from './wangEditor.vue'
export default {
  components: { treeProduct, uploadImg, wangEditor },
  computed: {
    ...mapState('product', ['rowData', 'title'])
  },
  data() {
    return {
      fileList: [],//图片集合
      wangEditor,
      ruleForm: {//表单数据
        id: '',
        title: '',
        num: '',
        price: '',
        sellPoint: '',
        image: [],
        descs: '',
        category: '',
        cid: '',
        isShow: true,
      },
      rules: {//表单验证
        title: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          //   { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        num: [
          { required: true, message: '请选择商品数量', trigger: 'change' }
        ],
        price: [
          { required: true, message: '请选择商品价格', trigger: 'change' }
        ],
        category: [
          { required: true, message: '请选择商品类目', trigger: 'change' }
        ],
      }
    };
  },
  methods: {
    closePage(){
      this.$router.push('/product/list')
    },
    sendImg(val) {
      // console.log('父亲接受到了子组件的图片路径',val);
      this.ruleForm.image.push(val)
    },
    sendWangEditor(val) {//接受到文本编译器的内容
      // console.log('接受到文本编译器的内容',val);
      this.ruleForm.descs = val
    },
    sendTreeData(val) {
      this.ruleForm.category = val.name;
      this.ruleForm.cid = val.cid
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let { id, title, image, sellPoint, price, cid, category, num, descs } = this.ruleForm
          if (this.title == '添加') {
            console.log('添加商品成功', this.ruleForm);
            //image数组转字符串
            this.insertTbItem({ title, image: JSON.stringify(image), sellPoint, price, cid, category, num, descs })
          } else {
            console.log('修改商品---', this.ruleForm)
            this.updateTbItem({ id, title, image: JSON.stringify(image), sellPoint, price, cid, category, num, descs })
          }
        }
      });
    },
    //重置商品
    resetForm(formName) {
      if (this.title == '添加') {
        this.$refs[formName].resetFields();
        this.$refs.upload.clear();//清空图片
        this.$refs.wangEditor.editor.clear();//清空编辑器内容
      } else {
        //编辑界面的重置操作
        console.log(this.ruleForm);
        console.log(this.rowData);
        //点击编辑时，表单数据赋值给vuex，表单和vuex数据是对象，改变表单内容会引起vuex
        //数据里复杂数据类型改变，因此要使用深拷贝 JSON.parse(JSON.stringify(xxx))
        let rowData = JSON.parse(JSON.stringify(this.rowData));
        this.ruleForm = rowData;
        this.ruleForm.isShow = true;
        let imgs = rowData.image;//字符串
        let arr = JSON.parse(imgs)//去字符串并赋值
        this.ruleForm.image = arr
        console.log('编辑时把vuex图片传入表单', this.ruleForm.image);
        this.fileList=[];
        arr.forEach(ele => {
          this.fileList.push({ name: '', url: ele })
          // console.log('this.filesList',this.filesList);
        });
        this.$nextTick(() => {
          this.$refs.wangEditor.html = rowData.descs;
        })
      }

    },
    //修改商品
    async updateTbItem(params) {
      let res = await this.$api.updateTbItem(params);
      console.log('修改商品---', res.data);
      if (res.data.status === 200) {
        this.$message({
          message: '恭喜你，修改成功',
          type: 'success'
        });
        this.$router.push('/product/list')
      }
    },
    //添加商品
    async insertTbItem(params) {
      let res = await this.$api.insertTbItem(params)
      console.log('添加商品----', res.data);
      if (res.data.status === 200) {
        this.$message({
          message: '恭喜你，添加成功',
          type: 'success'
        });
        this.$router.push('/product/list')
      }
    }
  },
  created() {

  },
  mounted() {
    if (this.title == '编辑' || this.title == '详情') {
      //点击编辑时，表单数据赋值给vuex，表单和vuex数据是对象，改变表单内容会引起vuex
      //数据里复杂数据类型改变，因此要使用深拷贝 JSON.parse(JSON.stringify(xxx))
     
      this.ruleForm = JSON.parse(JSON.stringify(this.rowData));
      this.ruleForm.isShow = true;
      let imgs = this.ruleForm.image;//字符串
      this.ruleForm.image = JSON.parse(imgs)//去字符串并赋值
      console.log('编辑时把vuex图片传入表单', this.ruleForm.image);
      this.ruleForm.image.forEach(ele => {
        this.fileList.push({ name: '', url: ele })
        // console.log('this.filesList',this.filesList);
      });
      this.$nextTick(() => {
        this.$refs.wangEditor.html =this.rowData.descs;
      })
    }

  }
}
</script>
<style lang="less" scoped>
.nav {
  height: 600px;
  background: #fff;
  .nav-title {
    background-color: #606266;
    padding: 20px;
    color: #fff;
  }
  .treeProduct {
    padding: 20px;
  }
}
.wrapper {
  background: #fff;
  .wrapper-title {
    background-color: #606266;
    padding: 20px;
    color: #fff;
    margin-bottom: 10px;
  }
  .demo-ruleForm {
    padding: 20px;
  }
}
</style>